import { observable, action, runInAction } from 'mobx-miniprogram';
import { standardizeModuleStore } from '../../../store/helpers/store_standardizer.js';
import baseStore from '../../../store/global/base_store.js';
import dayjs from 'dayjs';

const resourceStore = observable({
  // 状态数据
  resourceList: [],
  resourceDetail: null,
  versionList: [],
  versionDetail: null,
  versionComparison: null,
  isLoading: false,
  errorMessage: '',
  
  // 资源类型枚举
  RESOURCE_TYPE: {
    PCB: 0,
    BOM: 1,
    SCHEMATIC: 2,
    PACKAGING: 3,
    PROCESSING: 4,
    SOFTWARE: 5,
    SPEC: 6
  },
  
  // 版本状态枚举
  VERSION_STATUS: {
    DRAFT: 1,
    RELEASED: 2,
    PRODUCTION: 3,
    CUSTOMER_APPROVED: 4,
    DEPRECATED: 5
  },
  
  // 引用类型枚举
  REFERENCE_TYPE: {
    INPUT: 1,
    OUTPUT: 2,
    REFERENCE: 3
  },
  
  // 获取版本状态名称
  getVersionStatusName(status) {
    const statusNames = {
      [this.VERSION_STATUS.DRAFT]: '草稿',
      [this.VERSION_STATUS.RELEASED]: '已发布',
      [this.VERSION_STATUS.PRODUCTION]: '生产版本',
      [this.VERSION_STATUS.CUSTOMER_APPROVED]: '客户确认版本',
      [this.VERSION_STATUS.DEPRECATED]: '已废弃'
    };
    return statusNames[status] || '未知';
  },
  
  // 获取资源类型名称
  getResourceTypeName(type) {
    const typeNames = {
      [this.RESOURCE_TYPE.PCB]: 'PCB',
      [this.RESOURCE_TYPE.BOM]: 'BOM',
      [this.RESOURCE_TYPE.SCHEMATIC]: '原理图',
      [this.RESOURCE_TYPE.PACKAGING]: '包装指引',
      [this.RESOURCE_TYPE.PROCESSING]: '加工指引',
      [this.RESOURCE_TYPE.SOFTWARE]: '软件',
      [this.RESOURCE_TYPE.SPEC]: '规格书'
    };
    return typeNames[type] || '未知';
  },
  
  // 获取引用类型名称
  getRefTypeName(type) {
    const refTypeNames = {
      [this.REFERENCE_TYPE.INPUT]: '输入',
      [this.REFERENCE_TYPE.OUTPUT]: '输出',
      [this.REFERENCE_TYPE.REFERENCE]: '参考'
    };
    return refTypeNames[type] || '未知';
  },
  
  // 生成版本号
  generateVersionNumber(currentVersion) {
    if (!currentVersion) return 'v1.0.0';
    
    // 去掉开头的v
    let version = currentVersion;
    if (version.startsWith('v')) {
      version = version.substring(1);
    }
    
    // 尝试解析语义化版本号
    const parts = version.split('.');
    if (parts.length === 3) {
      const major = parseInt(parts[0], 10);
      const minor = parseInt(parts[1], 10);
      const patch = parseInt(parts[2], 10);
      
      // 增加补丁版本
      return `v${major}.${minor}.${patch + 1}`;
    } else if (parts.length === 2) {
      const major = parseInt(parts[0], 10);
      const minor = parseInt(parts[1], 10);
      
      // 增加小版本
      return `v${major}.${minor + 1}.0`;
    } else {
      // 无法解析，使用日期作为版本号
      return `v${dayjs().format('YYYY.MM.DD')}`;
    }
  },
  
  // 格式化版本号
  formatVersion(version) {
    if (!version) return 'v1.0.0';
    if (!version.startsWith('v')) {
      return `v${version}`;
    }
    return version;
  },
  
  // 格式化版本比较结果
  formatComparisonResult(comparison) {
    if (!comparison) return null;
    
    // 处理比较结果元数据
    const metadata = {
      oldVersion: comparison.oldVersion || {},
      newVersion: comparison.newVersion || {},
      diffs: comparison.diffs || {},
      stats: comparison.stats || {
        added: 0,
        modified: 0,
        removed: 0
      }
    };
    
    // 添加版本之间的时间差
    if (metadata.oldVersion.CREATE_TIME && metadata.newVersion.CREATE_TIME) {
      const oldTime = dayjs.unix(metadata.oldVersion.CREATE_TIME);
      const newTime = dayjs.unix(metadata.newVersion.CREATE_TIME);
      metadata.timeDiff = newTime.diff(oldTime, 'day');
    }
    
    return metadata;
  },
  
  // 检查两个版本是否有依赖关系
  checkVersionDependency(versionA, versionB) {
    if (!versionA || !versionB) return false;
    
    // 检查父子关系
    if (versionA.PARENT_VERSION === versionB._id || versionB.PARENT_VERSION === versionA._id) {
      return true;
    }
    
    // 检查依赖列表
    if (versionA.DEPENDENCIES && versionA.DEPENDENCIES.includes(versionB._id)) {
      return true;
    }
    
    if (versionB.DEPENDENCIES && versionB.DEPENDENCIES.includes(versionA._id)) {
      return true;
    }
    
    return false;
  },
  
  // 将资源连接到状态历史
  linkResourceToState(resource, stateHistoryId, referenceType = 1) {
    return {
      RESOURCE_ID: resource._id,
      VERSION_ID: resource.currentVersionId,
      REFERENCE_TYPE: referenceType,
      METADATA: {
        NAME: resource.RESOURCE_NAME,
        DESC: resource.RESOURCE_DESC || '',
        STATUS: resource.VERSION_STATUS,
        CREATE_TIME: resource.CREATE_TIME
      }
    };
  },
  
  // Actions
  
  // 获取资源列表
  fetchResourceList: action(async function(projectId, options = {}) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
      });
      
      const { page = 1, size = 10, filter, sort } = options;
      const params = { projectId, page, size };
      
      if (filter && filter.type) {
        params.resourceType = filter.type;
      }
      
      if (sort) {
        params.sortField = sort.field;
        params.sortOrder = sort.order;
      }
      
      const result = await baseStore.cloudCall('research/get_resources', params);
      
      runInAction(() => {
        this.resourceList = result.list || [];
        this.isLoading = false;
      });
      
      return this.resourceList;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '获取资源列表失败';
      });
      throw error;
    }
  }),
  
  // 获取资源详情
  fetchResourceDetail: action(async function(resourceId) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
      });
      
      const result = await baseStore.cloudCall('research/get_resource_detail', { resourceId });
      
      runInAction(() => {
        this.resourceDetail = result;
        this.isLoading = false;
      });
      
      return this.resourceDetail;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '获取资源详情失败';
      });
      throw error;
    }
  }),
  
  // 获取资源版本列表
  fetchVersionList: action(async function(resourceId, options = {}) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
      });
      
      const { page = 1, size = 10 } = options;
      const result = await baseStore.cloudCall('research/get_resource_versions', { 
        resourceId, 
        page, 
        size 
      });
      
      runInAction(() => {
        this.versionList = result.list || [];
        this.isLoading = false;
      });
      
      return this.versionList;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '获取版本列表失败';
      });
      throw error;
    }
  }),
  
  // 获取版本详情
  fetchVersionDetail: action(async function(versionId) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
      });
      
      const result = await baseStore.cloudCall('research/get_version_detail', { versionId });
      
      runInAction(() => {
        this.versionDetail = result;
        this.isLoading = false;
      });
      
      return this.versionDetail;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '获取版本详情失败';
      });
      throw error;
    }
  }),
  
  // 创建版本
  createVersion: action(async function(resourceId, versionData) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
      });
      
      const params = {
        resourceId,
        ...versionData
      };
      
      const result = await baseStore.cloudCall('research/create_version', params);
      
      runInAction(() => {
        this.isLoading = false;
        // 如果版本列表已加载，则添加新版本
        if (this.versionList && this.versionList.length > 0) {
          this.versionList.unshift(result);
        }
      });
      
      return result;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '创建版本失败';
      });
      throw error;
    }
  }),
  
  // 比较版本
  compareVersions: action(async function(resourceId, versionA, versionB) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
        this.versionComparison = null;
      });
      
      const result = await baseStore.cloudCall('research/compare_versions', {
        resourceId,
        versionA,
        versionB
      });
      
      runInAction(() => {
        this.versionComparison = this.formatComparisonResult(result);
        this.isLoading = false;
      });
      
      return this.versionComparison;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '比较版本失败';
      });
      throw error;
    }
  }),
  
  // 设置当前版本
  setCurrentVersion: action(async function(resourceId, versionId) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
      });
      
      const result = await baseStore.cloudCall('research/set_current_version', {
        resourceId,
        versionId
      });
      
      runInAction(() => {
        this.isLoading = false;
        
        // 更新资源详情中的当前版本
        if (this.resourceDetail && this.resourceDetail._id === resourceId) {
          this.resourceDetail.CURRENT_VERSION_ID = versionId;
        }
        
        // 更新版本列表中的当前版本标记
        if (this.versionList && this.versionList.length > 0) {
          this.versionList = this.versionList.map(version => ({
            ...version,
            IS_CURRENT: version._id === versionId ? 1 : 0
          }));
        }
      });
      
      return result;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '设置当前版本失败';
      });
      throw error;
    }
  }),
  
  // 添加依赖关系
  addDependency: action(async function(sourceId, targetId, type) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
      });
      
      const result = await baseStore.cloudCall('research/add_dependency', {
        sourceId,
        targetId,
        type
      });
      
      runInAction(() => {
        this.isLoading = false;
        
        // 更新版本详情中的依赖
        if (this.versionDetail && this.versionDetail._id === sourceId) {
          if (!this.versionDetail.DEPENDENCIES) {
            this.versionDetail.DEPENDENCIES = [];
          }
          this.versionDetail.DEPENDENCIES.push({
            TARGET_ID: targetId,
            TYPE: type
          });
        }
      });
      
      return result;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '添加依赖关系失败';
      });
      throw error;
    }
  }),
  
  // 获取依赖图
  getDependencyGraph: action(async function(resourceId, depth = 1) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
      });
      
      const result = await baseStore.cloudCall('research/get_dependency_graph', {
        resourceId,
        depth
      });
      
      runInAction(() => {
        this.isLoading = false;
      });
      
      return result;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '获取依赖图失败';
      });
      throw error;
    }
  }),
  
  // 获取受影响资源
  getImpactedResources: action(async function(resourceId, versionId) {
    try {
      runInAction(() => {
        this.isLoading = true;
        this.errorMessage = '';
      });
      
      const result = await baseStore.cloudCall('research/get_impacted_resources', {
        resourceId,
        versionId
      });
      
      runInAction(() => {
        this.isLoading = false;
      });
      
      return result;
    } catch (error) {
      runInAction(() => {
        this.isLoading = false;
        this.errorMessage = error.message || '获取受影响资源失败';
      });
      throw error;
    }
  }),
  
  // 清理
  clearResourceDetail: action(function() {
    this.resourceDetail = null;
  }),
  
  clearVersionList: action(function() {
    this.versionList = [];
  }),
  
  clearVersionDetail: action(function() {
    this.versionDetail = null;
  }),
  
  clearVersionComparison: action(function() {
    this.versionComparison = null;
  }),
  
  clearAll: action(function() {
    this.resourceList = [];
    this.resourceDetail = null;
    this.versionList = [];
    this.versionDetail = null;
    this.versionComparison = null;
    this.errorMessage = '';
  })
});

// 标准化模块Store
export const ResourceStore = standardizeModuleStore(resourceStore); 